package com.dong.i18n_demo;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

public class MyLocaleResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        //得到cookie,解析locale
        Cookie[] cookies = httpServletRequest.getCookies();
        Locale locale = Locale.getDefault();
        if(cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("accept_language")) {
                    String temp = cookie.getValue();
                    if (!StringUtils.isEmpty(temp)) {
                        String[] s = temp.split("_");
                        locale = new Locale(s[0],s[1]);
                    }
                }
            }
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}